---
title: "Replication Material for: 'Broad and detailed agreement: Public preferences for German immigration policy'"
author: "Marc Helbling, Felix Jäger, Rahsaan Maxwell and Richard Traunmüller"
date: "`r format(Sys.time(), '%d %B, %Y')`"
header-includes:
  - \usepackage{flafter}
output: 
  pdf_document: 
      latex_engine: xelatex

---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
stargazer_opt <- ifelse(knitr::is_latex_output(), "latex", "html")
p_needed <-
  c("knitr", "cjoint", "lme4" , "stringr", "stargazer","RColorBrewer")

packages <- rownames(installed.packages())

p_to_install <- p_needed[!(p_needed %in% packages)]

if (length(p_to_install) > 0) {
  install.packages(p_to_install)
}

sapply(p_needed, require, character.only = TRUE)
```


```{r export figures to separate pdf files, include=FALSE}
plots_to_pdf <- T
```


```{r load functions}
for(i in list.files("custom_functions")) {
  source(paste0("custom_functions/",i))
}
```

```{r load data}
for(i in list.files("data")) {
  load(paste0("data/", i))
}
```

# Main section: three entry gates in comparison

```{r dimension labels of the three factorial experiments immigration integration naturalization}
# Create vectors with the dimensions (objectsnames and "real" names)
exp1_cat <- colnames(df_conj_fac)[which(names(df_conj_fac)=="ImmPolicygoal"):which(names(df_conj_fac)=="ImmChangejobsector")]
exp1_cat_labels <- c("Policy goal", "Economic requirement", "Language requirement", "Integration requirement", "Labor market requirement", 
                     "Duration work permit", "Renewal work permit", "Withdrawal work permit", "Work conditions and benefits", "Change job sector")

exp2_cat <- colnames(df_conj_fac)[which(names(df_conj_fac)=="IntPolicygoal"):which(names(df_conj_fac)=="IntAccesspoliticalrights")]
exp2_cat_labels <- c("Policy goal", "Required time residence", "Economic requirement", "Language requirement", "Integration requirement", 
                     "Renewal residence permit", "Withdrawal residence permit", "Access employment", "Access social security", "Access political rights")

exp3_cat <- colnames(df_conj_fac)[which(names(df_conj_fac)=="NatPolicygoal"):which(names(df_conj_fac)=="NatDualcitizenship")]
exp3_cat_labels <- c("Policy goal", "Required time residence", "Economic requirement", "Language requirement", "Integration requirement", 
                     "Required criminal record", "Withdrawal citizenship", "Citizenship descendents", "Dual citizenship")
```


```{r attribute labels}
attr_names_exp1 <- c("Not possible","1 year", "3 years", "5 years", "Minimum Wage", "Pass integration test", "Complete integration course", "Only accept if no native can do job", "Advanced language skills", "Basic language lkills", "Restrict immigration", "Encourage immigration", "If job is lost", "Better for nationals", "Equal to nationals")

attr_names_exp2 <- c("Yes but priority for nationals", "Yes equal to nationals", "Voting rights on local level", "On local and national level", "No use of social assistance", "Pass integration test", "Complete integration course", "Advanced language skills", "Basic language skills", "Restrict integration", "Encourage integration", "Upon application","10 years", "5 years", "3 year", "If convicted of serious crime")

attr_names_exp3  <- c("Upon regular application", "Upon facilitated application", "Automatically at birth", "Not allowed", "Minimum wage" ,"Pass integration test", "Complete integration course", "Advanced language skills", "Basic language skills", "Restrict naturalization", "Encourage naturalization","Reject if convicted of serious crime", "Reject if convicted of minor offense", "15 years", "8 years", "2 year", "If convicted of serious crime")
```


```{r merge-conjoints-with-respondent-data, echo=F}
conj_and_resp <- merge(df_conj_fac, data, by="resp_id")
```

```{r formulas-for-each-experiment, echo=F}
formular_exp1_Imm <- Immchoice ~ ImmPolicygoal + ImmEconomicrequirement + 
                    ImmLanguagerequirement + ImmIntegrationrequirement + 
                    ImmLabormarketrequirement + ImmDurationworkpermit + 
                    ImmRenewalworkpermit + ImmWithdrawalworkpermit + 
                    ImmWorkconditionsandbenefits + ImmChangejobsector    

formular_exp2_Int <- Intchoice ~ IntPolicygoal + IntRequiredtimeresidence + 
                    IntEconomicrequirement + IntLanguagerequirement + 
                    IntIntegrationrequirement + IntRenewalresidencepermit + 
                    IntWithdrawalresidencepermit + IntAccessemployment + 
                    IntAccesssocialsecurity + IntAccesspoliticalrights

formular_exp3_Nat <- Natchoice ~ NatPolicygoal + NatRequiredtimeresidence + 
                    NatEconomicrequirement + NatLanguagerequirement + 
                    NatIntegrationrequirement + NatRequiredcriminalrecord + 
                    NatWithdrawalcitizenship + NatCitizenshipdescendents + 
                    NatDualcitizenship           
```


```{r calculate-amce-for-all-3-models, echo=F, warning=F, include=F}
amce_mod_1 <- cjoint::amce(formula = formular_exp1_Imm,
                data=df_conj_fac[!is.na(df_conj_fac$Immchoice),], respondent.id="resp_id")


amce_mod_2 <- cjoint::amce(formula = formular_exp2_Int,
                data=df_conj_fac[!is.na(df_conj_fac$Intchoice),], respondent.id="resp_id")


amce_mod_3 <- cjoint::amce(formula = formular_exp3_Nat,
                data=df_conj_fac[!is.na(df_conj_fac$Natchoice),], respondent.id="resp_id")
```

```{r correcting-the-labels}
names(amce_mod_1$attributes) <- c("Change job sector","Duration work permit","Economic requirement", "Integration requirement", "Labor market requirement", "Language requirement", "Policy goal", "Renewal work permit", "Withdrawal work permit", "Work conditions and benefits")
amce_mod_1$attributes[[1]][1] <- "Not possible"
amce_mod_1$attributes[[2]] <- c("1 year", "3 years", "5 years")
amce_mod_1$attributes[[3]][1] <- "Minimum wage"
amce_mod_1$attributes[[4]][1:2] <- c("Pass integration test", "Complete integration course")
amce_mod_1$attributes[[5]][1] <- "Only accept if no native can do job"
amce_mod_1$attributes[[6]][1:2] <- c("Advanced language skills", "Basic language skills")
amce_mod_1$attributes[[7]] <- c("Restrict immigration", "Encourage immigration")
amce_mod_1$attributes[[8]][1] <- "Not possible"
amce_mod_1$attributes[[9]][1] <- "If job is lost"
amce_mod_1$attributes[[10]] <- c("Better for nationals", "Equal to nationals")

names(amce_mod_2$attributes) <- c("Access employment", "Access political rights", "Access social security", "Economic requirement", "Integration requirement", "Language requirement", "Policy goal", "Renewal residence permit", "Required time residence", "Withdrawal residence permit")
amce_mod_2$attributes[[1]] <- c("Yes but priority for nationals", "Yes equal to nationals")
amce_mod_2$attributes[[2]][2:3] <- c("Voting rights on local level", "On local and national level")
amce_mod_2$attributes[[3]] <- c("Yes but priority for nationals", "Yes equal to nationals")
amce_mod_2$attributes[[4]][1] <- "No use of social assistance"
amce_mod_2$attributes[[5]][1:2] <- c("Pass integration test", "Complete integration course")
amce_mod_2$attributes[[6]][1:2] <- c("Advanced language skills", "Basic language skills")
amce_mod_2$attributes[[7]] <- c("Restrict integration", "Encourage integration")
amce_mod_2$attributes[[8]][1] <- "Upon application"
amce_mod_2$attributes[[9]] <- c("10 years", "5 years", "3 year")
amce_mod_2$attributes[[10]][1] <- "If convicted of serious crime"

names(amce_mod_3$attributes) <- c("Citizenship descendents", "Dual citizenship", "Economic requirement", "Integration requirement", "Language requirement", "Policy goal", "Required criminal record", "Required time residence", "Withdrawal citizenship")
amce_mod_3$attributes[[1]] <- c("Upon regular application", "Upon facilitated application", "Automatically at birth")
amce_mod_3$attributes[[2]][1] <- "Not allowed"
amce_mod_3$attributes[[3]][1] <- "Minimum wage" 
amce_mod_3$attributes[[4]][1:2] <- c("Pass integration test", "Complete integration course")
amce_mod_3$attributes[[5]][1:2] <- c("Advanced language skills", "Basic language skills")
amce_mod_3$attributes[[6]] <- c("Restrict naturalization", "Encourage naturalization")
amce_mod_3$attributes[[7]][1:2] <- c("Reject if convicted of serious crime", "Reject if convicted of minor offense")
amce_mod_3$attributes[[8]] <- c("15 years", "8 years", "2 year")
amce_mod_3$attributes[[9]][1] <- "If convicted of serious crime"
```


```{r custom-amce-plots-immigration, fig.height=7,fig.width=7}
dim_names <- names(amce_mod_1$attributes)
ord1 <- c("Economic", "Economic", "Economic", "Cultural", "Economic", "Cultural", "", "Economic", "Economic", "Economic")
ord2 <- c("Right", "Right", "Requirement", "Requirement", "Requirement", "Requirement", "Overall goal", "Right", "Requirement", "Right")
dim_and_order <- data.frame(dim_names, ord1, ord2)
dim_and_order_1 <- dim_and_order[order(dim_and_order$ord1, dim_and_order$ord2, unlist(lapply(amce_mod_1$estimates, function(x)min(x[1,])))),]
```

```{r custom-amce-plots-integration, fig.height=7,fig.width=7}
dim_names <- names(amce_mod_2$attributes)
ord1 <- c("Economic", "X", "Economic", "Economic", "Cultural", "Cultural", "", "Cultural", "Cultural", "Sec")
ord2 <- c("Right", "Right", "Right", "Requirement", "Requirement", "Requirement", "Overall goal", "Right", "Requirement", "Requirement")
dim_and_order <- data.frame(dim_names, ord1, ord2)
dim_and_order_2 <- dim_and_order[order(dim_and_order$ord1, dim_and_order$ord2, unlist(lapply(amce_mod_2$estimates, function(x)min(x[1,])))),]
```

```{r custom-amce-plots-naturalization, fig.height=7,fig.width=7}
dim_names <- names(amce_mod_3$attributes)
ord1 <- c("Cultural", "Cultural", "Econ", "Cultural", "Cultural", "", "Security", "Cultural", "Security")
ord2 <- c("Requirement", "Right", "Requirement", "Requirement", "Requirement", "Overall goal", "Requirement", "Requirement", "Requirement")
dim_and_order <- data.frame(dim_names, ord1, ord2)
dim_and_order_3 <- dim_and_order[order(dim_and_order$ord1, dim_and_order$ord2, unlist(lapply(amce_mod_3$estimates, function(x)min(x[1,])))),]
```

```{r}
dim_and_order_1$dim_names[4] <- "Economic requirement"
dim_and_order_2$dim_names[6] <- "Economic requirement"
dim_and_order_3$dim_names[7] <- "Economic requirement"
```


```{r three entry gates in comparison, fig.height=8, fig.width=7}
if(plots_to_pdf){pdf("output/output_figures_main/figure_three_entry_gates_immigration.pdf", height=8, width=7)}
  custom_amce_plot(amce_mod_1, dim_and_order_1, plot_title="Immigration",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB", 
                   bonf_corr = T, legend_inset_x = -.2, legend_inset = -.18)
if(plots_to_pdf){dev.off()}
  
if(plots_to_pdf){pdf("output/output_figures_main/figure_three_entry_gates_integration.pdf", height=8, width=7)}
  custom_amce_plot(amce_mod_2, dim_and_order_2, plot_title="Integration",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB",
                   bonf_corr = T, legend_inset_x = -.2, legend_inset = -.18)
if(plots_to_pdf){dev.off()}
  
if(plots_to_pdf){pdf("output/output_figures_main/figure_three_entry_gates_naturalization.pdf", height=8, width=7)}
  custom_amce_plot(amce_mod_3, dim_and_order_3, plot_title="Naturalization",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB",
                   bonf_corr = T, legend_inset_x = -.2, legend_inset = -.18)
if(plots_to_pdf){dev.off()}
```

```{r three entry gates in comparison as eps file}
if(plots_to_pdf){
  postscript("output/output_figures_main/figure_1.eps", height = 8, width = 7)
  custom_amce_plot(amce_mod_1, dim_and_order_1, plot_title="Immigration",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB", 
                   bonf_corr = T, legend_inset_x = -.2, legend_inset = -.18)
dev.off()
}

if(plots_to_pdf){
  postscript("output/output_figures_main/figure_2.eps", height=8, width=7)
  custom_amce_plot(amce_mod_2, dim_and_order_2, plot_title="Integration",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB",
                   bonf_corr = T, legend_inset_x = -.2, legend_inset = -.18)
dev.off()}
  
if(plots_to_pdf){
  postscript("output/output_figures_main/figure_3.eps", height=8, width=7)
  custom_amce_plot(amce_mod_3, dim_and_order_3, plot_title="Naturalization",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB",
                   bonf_corr = T, legend_inset_x = -.2, legend_inset = -.18)
dev.off()}
```


```{r three entry gates in comparison as tiff file}
if(plots_to_pdf){
  bitmap("output/output_figures_main/figure_1.tiff", height = 8, width = 7, units = 'in', type="tiff24nc", res=500)
  custom_amce_plot(amce_mod_1, dim_and_order_1, plot_title="Immigration",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB", 
                   bonf_corr = T, legend_inset_x = -.16, legend_inset = -.15)
dev.off()
}

  
if(plots_to_pdf){
  bitmap("output/output_figures_main/figure_2.tiff", height = 8, width = 7, units = 'in', type="tiff24nc", res=500)
  custom_amce_plot(amce_mod_2, dim_and_order_2, plot_title="Integration",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB",
                   bonf_corr = T, legend_inset_x = -.16, legend_inset = -.15)
dev.off()}
  
if(plots_to_pdf){
  bitmap("output/output_figures_main/figure_3.tiff", height = 8, width = 7, units = 'in', type="tiff24nc", res=500)
  custom_amce_plot(amce_mod_3, dim_and_order_3, plot_title="Naturalization",  
                   show_cat_in_plot = F, add_legend = F, col_override = "#8DA0CB",
                   bonf_corr = T, legend_inset_x = -.16, legend_inset = -.15)
dev.off()}
```

\newpage

# Appendix

## Subgroups by Populism

```{r populism-scale-items, echo=F}
data_pop_scale <- data[,which(names(data)=="populism_1"):which(names(data)=="populism_12")]
data_pop_scale <- data.frame(apply(data_pop_scale, 2, as.character))
for (i in 1:ncol(data_pop_scale)) {
  data_pop_scale[,i] <- ifelse(data_pop_scale[,i]=="-99", NA, data_pop_scale[,i])
  data_pop_scale[,i] <- str_replace_all(data_pop_scale[,i], "stimme überhaupt nicht zu", "1")
  data_pop_scale[,i] <- str_replace_all(data_pop_scale[,i], "stimme eher nicht zu", "2")
  data_pop_scale[,i] <- str_replace_all(data_pop_scale[,i], "teils-teils", "3")
  data_pop_scale[,i] <- str_replace_all(data_pop_scale[,i], "stimme eher zu", "4")
  data_pop_scale[,i] <- str_replace_all(data_pop_scale[,i], "stimme voll und ganz zu", "5")
  data_pop_scale[,i] <- as.numeric(data_pop_scale[,i])
}
```

```{r populism-index-creation, echo=F, fig.width=6}
data_pop_scale$populism_index <- rowSums(data_pop_scale, na.rm=T)/(ncol(data_pop_scale)-apply(data_pop_scale, 1, function(x) sum(is.na(x))))
  data$populism_index <- data_pop_scale$populism_index
```


```{r populism-index-distribution, echo=F, fig.width=6}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_populism_distribution.pdf", height=4, width = 6)}
  hist(data$populism_index, las=1, border=F, xlab="Index", main="Populism index")
if(plots_to_pdf){dev.off()}
```


```{r populism-cat-overview, echo=F, fig.width=6, include=F}
data$populism_index_cat <- NA

data$populism_index_cat <- ifelse(data$populism_index<=mean(data$populism_index), "Low",
                                 ifelse(data$populism_index>mean(data$populism_index), "High", data$populism_index_cat))
quick_barplot(data$populism_index_cat)   


data$populism_index_cat2 <- ifelse(data$populism_index<=quantile(data$populism_index, .1), "Low",
                                 ifelse(data$populism_index>=quantile(data$populism_index, .9), "High", NA))
```


### Three entry gates by populism (amce)

```{r merge-populism-index-to-conj-data, echo=F}
df_pop <- data[,c("populism_index", "populism_index_cat", "populism_index_cat2", "resp_id")]
conj_and_resp <- merge(conj_and_resp, df_pop, by="resp_id")
conj_and_resp$populism_index_cat <- factor(conj_and_resp$populism_index_cat, levels=c("Low", "High"))
conj_and_resp$populism_index_cat2 <- factor(conj_and_resp$populism_index_cat2, levels=c("Low", "High"))
```

```{r set-up-for-subgroup-populism-plots}
amce_more_pop_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$populism_index_cat =="High" ,], respondent.id="resp_id")
amce_less_pop_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$populism_index_cat =="Low" ,], respondent.id="resp_id")
amce_more_pop_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$populism_index_cat =="High" ,], respondent.id="resp_id")
amce_less_pop_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$populism_index_cat =="Low" ,], respondent.id="resp_id")
amce_more_pop_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$populism_index_cat =="High" ,], respondent.id="resp_id")
amce_less_pop_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$populism_index_cat =="Low" ,], respondent.id="resp_id")

amce_more_pop_immi <- amce_replace_dim_names(amce_more_pop_immi, exp1_cat_labels, attr_names_exp1)  
amce_less_pop_immi <- amce_replace_dim_names(amce_less_pop_immi, exp1_cat_labels, attr_names_exp1) 

amce_more_pop_int <- amce_replace_dim_names(amce_more_pop_int, exp2_cat_labels, attr_names_exp2)  
amce_less_pop_int <- amce_replace_dim_names(amce_less_pop_int, exp2_cat_labels, attr_names_exp2) 

amce_more_pop_nat <- amce_replace_dim_names(amce_more_pop_nat, exp3_cat_labels, attr_names_exp3)  
amce_less_pop_nat <- amce_replace_dim_names(amce_less_pop_nat, exp3_cat_labels, attr_names_exp3) 


amce_pop_immi_attr <- list(amce_more_pop_immi$attributes,
                      amce_less_pop_immi$attributes)

amce_pop_immi_esti  <- list(amce_more_pop_immi$estimates,
                      amce_less_pop_immi$estimates)

dim_and_order_temp_1 <- dim_and_order_1
dim_and_order_temp_1$dim_names[4] <- "Economic requirement"


amce_pop_int_attr <- list(amce_more_pop_int$attributes,
                      amce_less_pop_int$attributes)

amce_pop_int_esti  <- list(amce_more_pop_int$estimates,
                      amce_less_pop_int$estimates)

dim_and_order_temp_2 <- dim_and_order_2
dim_and_order_temp_2$dim_names[6] <- "Economic requirement"

amce_pop_nat_attr <- list(amce_more_pop_nat$attributes,
                      amce_less_pop_nat$attributes)

amce_pop_nat_esti  <- list(amce_more_pop_nat$estimates,
                      amce_less_pop_nat$estimates)

dim_and_order_temp_3 <- dim_and_order_3
dim_and_order_temp_3$dim_names[7] <- "Economic requirement"
```


```{r subgroup-populism, fig.height=9.5,fig.width=7.5, fig.cap='Subgroup analysis for more and less populist respondents. Reference categories are the most restricitve or demanding options.'}

if(plots_to_pdf){pdf("output/output_figures_appendix/figure_three_entry_gates_populism.pdf", height=9.5, width=7)}
  layout(matrix(c(1,1,2,2,1,1,2,2,4,3,3,4,4,3,3,4), byrow=T, ncol=4))
  custom_amce_comparison(amce_pop_immi_attr, amce_pop_immi_esti, dim_and_order_temp_1, offset = 0.3, xlim=c(-0.23,0.2), plot_title = "Immigration", my_col = RColorBrewer::brewer.pal(3, "Set2") [2:1])
  custom_amce_comparison(amce_pop_int_attr, amce_pop_int_esti, dim_and_order_temp_2, offset = 0.3, xlim=c(-0.23,0.2), plot_title = "Integration", my_col = RColorBrewer::brewer.pal(3, "Set2") [2:1])
  custom_amce_comparison(amce_pop_nat_attr, amce_pop_nat_esti, dim_and_order_temp_3, legend_text= c("High pop. (above mean)", "Low pop. (below mean)"), offset = 0.3, legend_inset = c(-.8,-0.2), xlim=c(-0.23,0.2), plot_title = "Naturalization", my_col = RColorBrewer::brewer.pal(3, "Set2") [2:1])
if(plots_to_pdf){dev.off()}
```

```{r subgroup-populism immigration latex table}
cjoint_amce_latex_output(list(amce_more_pop_immi, amce_less_pop_immi), dim_and_order_temp_1$dim_names)
```

```{r subgroup-populism integration latex table}
cjoint_amce_latex_output(list(amce_more_pop_int, amce_less_pop_int), dim_and_order_temp_2$dim_names)
```

```{r subgroup-populism naturalization latex table}
cjoint_amce_latex_output(list(amce_more_pop_nat, amce_less_pop_nat), dim_and_order_temp_3$dim_names)
```

### Three entry gates by populism (mm)

```{r subgroup populism results immigration marginal means}
conj_and_resp_mm <- conj_and_resp

replace_factors_imm <- replace_duplicate_factor_labels_across_variables(conj_and_resp_mm[,c("ImmPolicygoal", "ImmEconomicrequirement", "ImmLanguagerequirement",
                    "ImmIntegrationrequirement", "ImmLabormarketrequirement", "ImmDurationworkpermit",
                    "ImmRenewalworkpermit", "ImmWithdrawalworkpermit", "ImmWorkconditionsandbenefits", 
                    "ImmChangejobsector")])

conj_and_resp_mm[,c("ImmPolicygoal", "ImmEconomicrequirement", "ImmLanguagerequirement",
                    "ImmIntegrationrequirement", "ImmLabormarketrequirement", "ImmDurationworkpermit",
                    "ImmRenewalworkpermit", "ImmWithdrawalworkpermit", "ImmWorkconditionsandbenefits", 
                    "ImmChangejobsector")] <- replace_factors_imm[[1]]

pop_imm_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Immchoice),],
          formula = formular_exp1_Imm, 
          id = ~ resp_id,
          by = ~ populism_index_cat,
          estimate = "mm")
```


```{r subgroup populism results integration marginal means}
replace_factors_int <- replace_duplicate_factor_labels_across_variables(conj_and_resp_mm[,c("IntPolicygoal", "IntRequiredtimeresidence", "IntEconomicrequirement",
                    "IntLanguagerequirement", "IntIntegrationrequirement", "IntRenewalresidencepermit",
                    "IntWithdrawalresidencepermit", "IntAccessemployment", "IntAccesssocialsecurity", 
                    "IntAccesspoliticalrights")])

conj_and_resp_mm[,c("IntPolicygoal", "IntRequiredtimeresidence", "IntEconomicrequirement",
                    "IntLanguagerequirement", "IntIntegrationrequirement", "IntRenewalresidencepermit",
                    "IntWithdrawalresidencepermit", "IntAccessemployment", "IntAccesssocialsecurity", 
                    "IntAccesspoliticalrights")] <- replace_factors_int[[1]]

pop_int_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Intchoice),],
          formula = formular_exp2_Int, 
          id = ~ resp_id,
          by = ~ populism_index_cat,
          estimate = "mm")
```


```{r subgroup populism results naturalization marginal means}
replace_factors_nat <- replace_duplicate_factor_labels_across_variables(conj_and_resp_mm[,c("NatPolicygoal", "NatRequiredtimeresidence", "NatEconomicrequirement",
    "NatLanguagerequirement", "NatIntegrationrequirement", "NatRequiredcriminalrecord",
    "NatWithdrawalcitizenship", "NatCitizenshipdescendents", "NatDualcitizenship")])

conj_and_resp_mm[,c("NatPolicygoal", "NatRequiredtimeresidence", "NatEconomicrequirement",
    "NatLanguagerequirement", "NatIntegrationrequirement", "NatRequiredcriminalrecord",
    "NatWithdrawalcitizenship", "NatCitizenshipdescendents", "NatDualcitizenship")] <- replace_factors_nat[[1]]

pop_nat_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Natchoice),],
          formula = formular_exp3_Nat, 
          id = ~ resp_id,
          by = ~ populism_index_cat,
          estimate = "mm")
```

```{r}
nice_dim_names_imm <- c("Policy goal", "Economic requirement", "Language requirement",
                    "Integration requirement", "Labor market requirement", "Duration work permit",
                    "Renewal work permit", "Withdrawal work permit", "Work conditions and benefits", 
                    "Change jobsector")

nice_dim_names_int <- c("Policy goal", "Required time residence", "Economic requirement", "Language requirement",
                    "Integration requirement", "Renewal residence permit", "Withdrawal residence permit", "Access employment", "Access social security", "Access political rights")

nice_dim_names_nat <- c("Policy goal", "Required time residence", "Economic requirement", "Language requirement",
                    "Integration requirement", "Required criminal record",
    "Withdrawal citizenship", "Citizenship descendents", "Dual citizenship")
```

```{r subgroup populism results marginal means plot, fig.height=9.5, fig.width=7}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_three_entry_gates_populism_mm.pdf", height=9.5, width=7)}
  layout(matrix(c(1,1,2,2,1,1,2,2,4,3,3,4,4,3,3,4), byrow=T, ncol=4))  
  custom_mm_plot(pop_imm_mm, replace_factors_imm[[2]], dim_names = nice_dim_names_imm, order_of_dimensions = c(1,3,4,2,8,5,6,9,10,7),
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), show_legend = F)
  custom_mm_plot(pop_int_mm, replace_factors_int[[2]], dim_names = nice_dim_names_int, order_of_dimensions = c(1,4,5,2,6,3,9,8,7,10), 
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), show_legend = F)
  custom_mm_plot(pop_nat_mm, replace_factors_nat[[2]], dim_names = nice_dim_names_nat, order_of_dimensions = c(1,4,5,8,2,9,3,7,6), 
                 xlim = c(0.35,0.65), legend_inset = c(-.8,-.2), show_legend = T, legend_text = c("low pop. (below mean)", "high pop. (above mean)"))
if(plots_to_pdf){dev.off()}
```


### Robustness populism with 10% lower and upper quantile (amce)

```{r set-up-for-subgroup-populism-plots}
amce_more_pop_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$populism_index_cat2 =="High" & !is.na(conj_and_resp$populism_index_cat2),], respondent.id="resp_id")
amce_less_pop_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$populism_index_cat2 =="Low"  & !is.na(conj_and_resp$populism_index_cat2),], respondent.id="resp_id")
amce_more_pop_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$populism_index_cat2 =="High"  & !is.na(conj_and_resp$populism_index_cat2),], respondent.id="resp_id")
amce_less_pop_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$populism_index_cat2 =="Low"  & !is.na(conj_and_resp$populism_index_cat2),], respondent.id="resp_id")
amce_more_pop_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$populism_index_cat2 =="High"  & !is.na(conj_and_resp$populism_index_cat2),], respondent.id="resp_id")
amce_less_pop_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$populism_index_cat2 =="Low"  & !is.na(conj_and_resp$populism_index_cat2),], respondent.id="resp_id")

amce_more_pop_immi <- amce_replace_dim_names(amce_more_pop_immi, exp1_cat_labels, attr_names_exp1)  
amce_less_pop_immi <- amce_replace_dim_names(amce_less_pop_immi, exp1_cat_labels, attr_names_exp1) 

amce_more_pop_int <- amce_replace_dim_names(amce_more_pop_int, exp2_cat_labels, attr_names_exp2)  
amce_less_pop_int <- amce_replace_dim_names(amce_less_pop_int, exp2_cat_labels, attr_names_exp2) 

amce_more_pop_nat <- amce_replace_dim_names(amce_more_pop_nat, exp3_cat_labels, attr_names_exp3)  
amce_less_pop_nat <- amce_replace_dim_names(amce_less_pop_nat, exp3_cat_labels, attr_names_exp3) 

amce_pop_immi_attr <- list(amce_more_pop_immi$attributes,
                      amce_less_pop_immi$attributes)

amce_pop_immi_esti  <- list(amce_more_pop_immi$estimates,
                      amce_less_pop_immi$estimates)

dim_and_order_temp_1 <- dim_and_order_1
dim_and_order_temp_1$dim_names[4] <- "Economic requirement"

amce_pop_int_attr <- list(amce_more_pop_int$attributes,
                      amce_less_pop_int$attributes)

amce_pop_int_esti  <- list(amce_more_pop_int$estimates,
                      amce_less_pop_int$estimates)

dim_and_order_temp_2 <- dim_and_order_2
dim_and_order_temp_2$dim_names[6] <- "Economic requirement"

amce_pop_nat_attr <- list(amce_more_pop_nat$attributes,
                      amce_less_pop_nat$attributes)

amce_pop_nat_esti  <- list(amce_more_pop_nat$estimates,
                      amce_less_pop_nat$estimates)

dim_and_order_temp_3 <- dim_and_order_3
dim_and_order_temp_3$dim_names[7] <- "Economic requirement"
```

```{r subgroup-populism, fig.height=9.5,fig.width=7.5, fig.cap='Subgroup analysis for more and less populist respondents. Reference categories are the most restricitve or demanding options.'}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_three_entry_gates_populism_robustness.pdf", height=9.5, width=7)}
  layout(matrix(c(1,1,2,2,1,1,2,2,4,3,3,4,4,3,3,4), byrow=T, ncol=4))
  custom_amce_comparison(amce_pop_immi_attr, amce_pop_immi_esti, dim_and_order_temp_1, offset = 0.3, xlim=c(-0.25,0.2), plot_title = "Immigration", my_col = RColorBrewer::brewer.pal(3, "Set2") [2:1])
  custom_amce_comparison(amce_pop_int_attr, amce_pop_int_esti, dim_and_order_temp_2, offset = 0.3, xlim=c(-0.25,0.2), plot_title = "Integration", my_col = RColorBrewer::brewer.pal(3, "Set2") [2:1])
  custom_amce_comparison(amce_pop_nat_attr, amce_pop_nat_esti, dim_and_order_temp_3, legend_text= c("High pop. (90%-quantile)", "Low pop. (10%-quantile)"), offset = 0.3, legend_inset = c(-1,-0.2), xlim=c(-0.25,0.2), plot_title = "Naturalization", my_col = RColorBrewer::brewer.pal(3, "Set2") [2:1])
if(plots_to_pdf){dev.off()}
```

```{r}
cjoint_amce_latex_output(list(amce_more_pop_immi, amce_less_pop_immi), dim_and_order_temp_1$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_more_pop_int, amce_less_pop_int), dim_and_order_temp_2$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_more_pop_nat, amce_less_pop_nat), dim_and_order_temp_3$dim_names)
```

### Robustness populism with 10% lower and upper quantile (mm)

```{r}
pop_imm_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Immchoice),],
          formula = formular_exp1_Imm, 
          id = ~ resp_id,
          by = ~ populism_index_cat2,
          estimate = "mm")

pop_int_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Intchoice),],
          formula = formular_exp2_Int, 
          id = ~ resp_id,
          by = ~ populism_index_cat2,
          estimate = "mm")

pop_nat_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Natchoice),],
          formula = formular_exp3_Nat, 
          id = ~ resp_id,
          by = ~ populism_index_cat2,
          estimate = "mm")
```

```{r, fig.height=9.5,fig.width=7.5}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_three_entry_gates_populism_robustness_mm.pdf", height=9.5, width=7)}
  layout(matrix(c(1,1,2,2,1,1,2,2,4,3,3,4,4,3,3,4), byrow=T, ncol=4))  
  custom_mm_plot(pop_imm_mm, replace_factors_imm[[2]], dim_names = nice_dim_names_imm, order_of_dimensions = c(1,3,4,2,8,5,6,9,10,7),
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), show_legend = F)
  custom_mm_plot(pop_int_mm, replace_factors_int[[2]], dim_names = nice_dim_names_int, order_of_dimensions = c(1,4,5,2,6,3,9,8,7,10), 
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), show_legend = F)
  custom_mm_plot(pop_nat_mm, replace_factors_nat[[2]], dim_names = nice_dim_names_nat, order_of_dimensions = c(1,4,5,8,2,9,3,7,6), 
                 xlim = c(0.35,0.65), legend_inset = c(-0.8,-.2), show_legend = T, legend_text = c("low pop. (10%-quantile)", "high pop. (90%-quantile)"))
if(plots_to_pdf){dev.off()}
```


\newpage

## Marginal means for whole sample

```{r}
whole_sample_imm_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Immchoice),],
          formula = formular_exp1_Imm, 
          id = ~ resp_id,
          estimate = "mm")

whole_sample_int_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Intchoice),],
          formula = formular_exp2_Int, 
          id = ~ resp_id,
          estimate = "mm")

whole_sample_nat_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Natchoice),],
          formula = formular_exp3_Nat, 
          id = ~ resp_id,
          estimate = "mm")
```

```{r, fig.height=9.5, fig.width=7}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_three_entry_gates_mm.pdf", height=9.5, width=7)}
  layout(matrix(c(1,1,2,2,1,1,2,2,4,3,3,4,4,3,3,4), byrow=T, ncol=4))  
  custom_mm_plot(whole_sample_imm_mm, replace_factors_imm[[2]], dim_names = nice_dim_names_imm, order_of_dimensions = c(1,3,4,2,8,5,6,9,10,7),
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), show_legend = F, my_col = "#8DA0CB")
  custom_mm_plot(whole_sample_int_mm, replace_factors_int[[2]], dim_names = nice_dim_names_int, order_of_dimensions = c(1,4,5,2,6,3,9,8,7,10), 
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), show_legend = F, my_col = "#8DA0CB")
  custom_mm_plot(whole_sample_nat_mm, replace_factors_nat[[2]], dim_names = nice_dim_names_nat, order_of_dimensions = c(1,4,5,8,2,9,3,7,6), 
                 xlim = c(0.35,0.65), legend_inset = c(-.8,-.2), show_legend = T, legend_text = c("low pop. (below mean)", "high pop. (above mean)"), my_col = "#8DA0CB")
if(plots_to_pdf){dev.off()}
```


## Subgroups by Party preference

```{r subgroup-partyvote-data-formatting, echo=F}
conj_and_resp$party_pref_clean <- conj_and_resp$party_pref
conj_and_resp$party_pref_clean <- ifelse(conj_and_resp$party_pref_clean=="" | conj_and_resp$party_pref_clean=="-99" | conj_and_resp$party_pref_clean=="Ich bin nicht wahlberechtigt", NA, conj_and_resp$party_pref_clean)
conj_and_resp$party_pref_clean <- as.factor(conj_and_resp$party_pref_clean)
levels(conj_and_resp$party_pref_clean) <- c("AfD", "Other", "Green", "CDU/CSU", "Left", "FDP", "Nonvoter", "SPD")
```


```{r subgroup-partyvote-plot, echo=F}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_preference.pdf", height=4, width = 6)}
par(mar=c(5,6,4,2))
barplot(sort(table(conj_and_resp$party_pref_clean)/sum(table(conj_and_resp$party_pref_clean)), decreasing=F), horiz=T, las=1, main="Party preference", xlab="Percentage", border=F, axes=F)
axis(1, at = seq(0,0.2,length.out = 5), labels = seq(0,0.2,length.out = 5)*100)
if(plots_to_pdf){dev.off()}
```

\newpage

### Three entry gates by party preference (amce)

```{r set-up-for-subgroup-parties-plots-immigration}
amce_afd_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$party_pref_clean =="AfD" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_green_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$party_pref_clean =="Green" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_cducsu_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$party_pref_clean =="CDU/CSU" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_left_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$party_pref_clean =="Left" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_fdp_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$party_pref_clean =="FDP" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_spd_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$party_pref_clean =="SPD" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")


amce_afd_immi <- amce_replace_dim_names(amce_afd_immi, exp1_cat_labels, attr_names_exp1)  
amce_green_immi <- amce_replace_dim_names(amce_green_immi, exp1_cat_labels, attr_names_exp1)  
amce_cducsu_immi <- amce_replace_dim_names(amce_cducsu_immi, exp1_cat_labels, attr_names_exp1)  
amce_left_immi <- amce_replace_dim_names(amce_left_immi, exp1_cat_labels, attr_names_exp1)  
amce_fdp_immi <- amce_replace_dim_names(amce_fdp_immi, exp1_cat_labels, attr_names_exp1)  
amce_spd_immi <- amce_replace_dim_names(amce_spd_immi, exp1_cat_labels, attr_names_exp1)  


amce_party_immi <- list(amce_afd_immi, amce_cducsu_immi,amce_fdp_immi,
                        amce_spd_immi,amce_green_immi,amce_left_immi)
names(amce_party_immi) <- c("afd", "cducsu", "fdp",
                            "spd" , "green", "left")

amce_party_immi_attr <- list(amce_afd_immi$attributes, amce_green_immi$attributes,
                           amce_cducsu_immi$attributes, amce_left_immi$attributes,
                           amce_fdp_immi$attributes, amce_spd_immi$attributes)

amce_party_immi_esti <- list(amce_afd_immi$estimates, amce_green_immi$estimates,
                           amce_cducsu_immi$estimates, amce_left_immi$estimates, 
                           amce_fdp_immi$estimates, amce_spd_immi$estimates)

dim_and_order_temp_1 <- dim_and_order_1
```

```{r set-up-for-subgroup-parties-plots-integration}
amce_afd_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$party_pref_clean =="AfD" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_green_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$party_pref_clean =="Green" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_cducsu_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$party_pref_clean =="CDU/CSU" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_left_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$party_pref_clean =="Left" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_fdp_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$party_pref_clean =="FDP" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_spd_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$party_pref_clean =="SPD" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")


amce_afd_int <- amce_replace_dim_names(amce_afd_int, exp2_cat_labels, attr_names_exp2)  
amce_green_int <- amce_replace_dim_names(amce_green_int, exp2_cat_labels, attr_names_exp2)  
amce_cducsu_int <- amce_replace_dim_names(amce_cducsu_int, exp2_cat_labels, attr_names_exp2)  
amce_left_int <- amce_replace_dim_names(amce_left_int, exp2_cat_labels, attr_names_exp2)  
amce_fdp_int <- amce_replace_dim_names(amce_fdp_int, exp2_cat_labels, attr_names_exp2)  
amce_spd_int <- amce_replace_dim_names(amce_spd_int, exp2_cat_labels, attr_names_exp2)  

amce_party_int_attr <- list(amce_afd_int$attributes, amce_green_int$attributes,
                           amce_cducsu_int$attributes, amce_left_int$attributes,
                           amce_fdp_int$attributes, amce_spd_int$attributes)

amce_party_int_esti <- list(amce_afd_int$estimates, amce_green_int$estimates,
                           amce_cducsu_int$estimates, amce_left_int$estimates, 
                           amce_fdp_int$estimates, amce_spd_int$estimates)

dim_and_order_temp_2 <- dim_and_order_2
```

```{r set-up-for-subgroup-parties-plots-naturalization}
amce_afd_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$party_pref_clean =="AfD" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_green_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$party_pref_clean =="Green" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_cducsu_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$party_pref_clean =="CDU/CSU" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_left_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$party_pref_clean =="Left" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_fdp_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$party_pref_clean =="FDP" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")
amce_spd_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$party_pref_clean =="SPD" & !is.na(conj_and_resp$party_pref_clean),], respondent.id="resp_id")

amce_afd_nat <- amce_replace_dim_names(amce_afd_nat, exp3_cat_labels, attr_names_exp3)  
amce_green_nat <- amce_replace_dim_names(amce_green_nat, exp3_cat_labels, attr_names_exp3)  
amce_cducsu_nat <- amce_replace_dim_names(amce_cducsu_nat, exp3_cat_labels, attr_names_exp3)  
amce_left_nat <- amce_replace_dim_names(amce_left_nat, exp3_cat_labels, attr_names_exp3)  
amce_fdp_nat <- amce_replace_dim_names(amce_fdp_nat, exp3_cat_labels, attr_names_exp3)  
amce_spd_nat <- amce_replace_dim_names(amce_spd_nat, exp3_cat_labels, attr_names_exp3)  

amce_party_nat_attr <- list(amce_afd_nat$attributes, amce_green_nat$attributes,
                           amce_cducsu_nat$attributes, amce_left_nat$attributes,
                           amce_fdp_nat$attributes, amce_spd_nat$attributes)

amce_party_nat_esti <- list(amce_afd_nat$estimates, amce_green_nat$estimates,
                           amce_cducsu_nat$estimates, amce_left_nat$estimates, 
                           amce_fdp_nat$estimates, amce_spd_nat$estimates)

dim_and_order_temp_3 <- dim_and_order_3

dim_and_order_temp_3$dim_names[7] <- "Economic requirement"
dim_and_order_temp_2$dim_names[6] <- "Economic requirement"
dim_and_order_temp_1$dim_names[4] <- "Economic requirement"
```



```{r subgroup-partyvote-immigration-two-plots1, fig.height=10,fig.width=7.5, include=T}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_immigration_part1.pdf", height=10, width = 7.5)}
amce_party_immi_attr_part1 <- lapply(amce_party_immi_attr, function(l) l[names(l)%in%dim_and_order_temp_1$dim_names[1:6]])
amce_party_immi_esti_part1 <- lapply(amce_party_immi_esti, function(l) l[names(l)%in%dim_and_order_temp_1$dim_names[1:6]])
custom_amce_comparison(amce_party_immi_attr_part1, amce_party_immi_esti_part1, dim_and_order_temp_1[1:6,], offset = 0.13, xlim=c(-0.25,0.2), plot_title = "Immigration policy goal and requirement", legend_text=c("AfD","Green","CDU/CSU", "Left", "FDP", "SPD"), legend_inset = c(-.35,-.14), my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}
```

```{r subgroup-partyvote-immigration-two-plots2, fig.height=6.6,fig.width=7.5, include=T}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_immigration_part2.pdf", height=6.6, width = 7.5)}
amce_party_immi_attr_part1 <- lapply(amce_party_immi_attr, function(l) l[names(l)%in%dim_and_order_temp_1$dim_names[7:10]])
amce_party_immi_esti_part1 <- lapply(amce_party_immi_esti, function(l) l[names(l)%in%dim_and_order_temp_1$dim_names[7:10]])
custom_amce_comparison(amce_party_immi_attr_part1, amce_party_immi_esti_part1, dim_and_order_temp_1[7:10,], offset = 0.13, xlim=c(-0.25,0.2), plot_title = "Immigration rights", legend_text=c("AfD","Green","CDU/CSU", "Left", "FDP", "SPD"), legend_inset = c(-.35,-.24), my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}
```

```{r subgroup-partyvote-integration-two-plots1, fig.height=10,fig.width=7.5, include=T}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_integration_part1.pdf", height=10, width = 7.5)}
amce_party_int_attr_part1 <- lapply(amce_party_int_attr, function(l) l[names(l)%in%dim_and_order_temp_2$dim_names[1:6]])
amce_party_int_esti_part1 <- lapply(amce_party_int_esti, function(l) l[names(l)%in%dim_and_order_temp_2$dim_names[1:6]])
custom_amce_comparison(amce_party_int_attr_part1, amce_party_int_esti_part1, dim_and_order_temp_2[1:6,], offset = 0.13, xlim=c(-0.25,0.2), plot_title = "Integration policy goal and requirement", legend_text=c("AfD","Green","CDU/CSU", "Left", "FDP", "SPD"), legend_inset = c(-.35,-.14), my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}
```

```{r subgroup-partyvote-integration-two-plots2, fig.height=6.6,fig.width=7.5, include=T}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_integration_part2.pdf", height=6.6, width = 7.5)}
amce_party_int_attr_part1 <- lapply(amce_party_int_attr, function(l) l[names(l)%in%dim_and_order_temp_2$dim_names[7:10]])
amce_party_int_esti_part1 <- lapply(amce_party_int_esti, function(l) l[names(l)%in%dim_and_order_temp_2$dim_names[7:10]])
custom_amce_comparison(amce_party_int_attr_part1, amce_party_int_esti_part1, dim_and_order_temp_2[7:10,], offset = 0.13, xlim=c(-0.25,0.2), plot_title = "Integration rights", legend_text=c("AfD","Green","CDU/CSU", "Left", "FDP", "SPD"), legend_inset = c(-.35,-.24), my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}
```

```{r subgroup-partyvote-naturalization-two-plots1, fig.height=10,fig.width=7.5, include=T}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_naturalization_part1.pdf", height=10, width = 7.5)}
amce_party_nat_attr_part1 <- lapply(amce_party_nat_attr, function(l) l[names(l)%in%dim_and_order_temp_3$dim_names[1:6]])
amce_party_nat_esti_part1 <- lapply(amce_party_nat_esti, function(l) l[names(l)%in%dim_and_order_temp_3$dim_names[1:6]])
custom_amce_comparison(amce_party_nat_attr_part1, amce_party_nat_esti_part1, dim_and_order_temp_3[1:6,], offset = 0.13, xlim=c(-0.25,0.2), plot_title = "Naturalization policy goal and requirement", legend_text=c("AfD","Green","CDU/CSU", "Left", "FDP", "SPD"), legend_inset = c(-.35,-.14), my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}
```

```{r subgroup-partyvote-naturalization-two-plots2, fig.height=6.6,fig.width=7.5, include=T}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_naturalization_part2.pdf", height=6.6, width = 7.5)}
amce_party_nat_attr_part1 <- lapply(amce_party_nat_attr, function(l) l[names(l)%in%dim_and_order_temp_3$dim_names[7:10]])
amce_party_nat_esti_part1 <- lapply(amce_party_nat_esti, function(l) l[names(l)%in%dim_and_order_temp_3$dim_names[7:10]])
custom_amce_comparison(amce_party_nat_attr_part1, amce_party_nat_esti_part1, dim_and_order_temp_3[7:10,], offset = 0.13, xlim=c(-0.25,0.2), plot_title = "Naturalization rights", legend_text=c("AfD","Green","CDU/CSU", "Left", "FDP", "SPD"), legend_inset = c(-.35,-.24), my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)], increase_ylim = 0.1)
if(plots_to_pdf){dev.off()}
```


```{r}
cjoint_amce_latex_output(list(amce_afd_immi, amce_cducsu_immi, amce_fdp_immi), dim_and_order_temp_1$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_green_immi, amce_left_immi, amce_spd_immi), dim_and_order_temp_1$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_afd_int, amce_cducsu_int, amce_fdp_int), dim_and_order_temp_2$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_green_int, amce_left_int, amce_spd_int), dim_and_order_temp_2$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_afd_nat, amce_cducsu_nat, amce_fdp_nat), dim_and_order_temp_3$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_green_nat, amce_left_nat, amce_spd_nat), dim_and_order_temp_3$dim_names)
```

### Three entry gates by party preference (mm)

```{r}
conj_and_resp_mm$party_pref_clean <- conj_and_resp_mm$party_pref
conj_and_resp_mm$party_pref_clean <- ifelse(conj_and_resp_mm$party_pref_clean=="" | conj_and_resp_mm$party_pref_clean=="-99" | conj_and_resp_mm$party_pref_clean=="Ich bin nicht wahlberechtigt" | conj_and_resp_mm$party_pref_clean=="Ich würde nicht wählen gehen" | conj_and_resp_mm$party_pref_clean=="Andere", NA, conj_and_resp_mm$party_pref_clean)
conj_and_resp_mm$party_pref_clean <- as.factor(conj_and_resp_mm$party_pref_clean)
levels(conj_and_resp_mm$party_pref_clean) <- c("AfD", "Greens", "CDU/CSU", "Left", "FDP", "SPD")
```

```{r}
party_imm_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Immchoice),],
          formula = formular_exp1_Imm, 
          id = ~ resp_id,
          by = ~ party_pref_clean,
          estimate = "mm")

party_int_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Intchoice),],
          formula = formular_exp2_Int, 
          id = ~ resp_id,
          by = ~ party_pref_clean,
          estimate = "mm")

party_nat_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Natchoice),],
          formula = formular_exp3_Nat, 
          id = ~ resp_id,
          by = ~ party_pref_clean,
          estimate = "mm")
```


```{r, fig.height=9.5,fig.width=7.5}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_immigration_mm_part1.pdf", height=11, width=7.5)}
  custom_mm_plot(party_imm_mm[party_imm_mm$feature%in%c("ImmPolicygoal", "ImmLanguagerequirement", "ImmIntegrationrequirement", "ImmEconomicrequirement", "ImmWithdrawalworkpermit", "ImmLabormarketrequirement"),], 
                 replace_factors_imm[[2]][c(1,2,3,4,5,8)], dim_names = nice_dim_names_imm[c(1,2,3,4,5,8)], order_of_dimensions = c(1,3,4,2,5,6),
                 xlim = c(0.35,0.65), legend_inset = c(-.3,-.13), show_legend = T, my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}  

if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_immigration_mm_part2.pdf", height=8, width=7.5)}
  custom_mm_plot(party_imm_mm[!party_imm_mm$feature%in%c("ImmPolicygoal", "ImmLanguagerequirement", "ImmIntegrationrequirement", "ImmEconomicrequirement", "ImmWithdrawalworkpermit", "ImmLabormarketrequirement"),], 
                 replace_factors_imm[[2]][c(6,7,9,10)], dim_names = nice_dim_names_imm[c(6,7,9,10)], order_of_dimensions = c(1,3,4,2),
                 xlim = c(0.35,0.65), legend_inset = c(-.3,-.2), show_legend = T, my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)],
                 increase_ylim = .2)
if(plots_to_pdf){dev.off()}
```


```{r, fig.height=9.5,fig.width=7.5}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_integration_mm_part1.pdf", height=11, width=7.5)}  
  custom_mm_plot(party_int_mm[party_int_mm$feature%in%c("IntPolicygoal", "IntLanguagerequirement", "IntIntegrationrequirement", "IntRequiredtimeresidence", "IntRenewalresidencepermit", "IntEconomicrequirement"),],
                 replace_factors_int[[2]][c(1,2,3,4,5,6)], dim_names = nice_dim_names_int[c(1,2,3,4,5,6)], order_of_dimensions = c(1,4,5,2,6,3), 
                 xlim = c(0.35,0.65), legend_inset = c(-.3,-.13), show_legend = T, my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}  
  
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_integration_mm_part2.pdf", height=8, width=7.5)}  
  custom_mm_plot(party_int_mm[!party_int_mm$feature%in%c("IntPolicygoal", "IntLanguagerequirement", "IntIntegrationrequirement", "IntRequiredtimeresidence", "IntRenewalresidencepermit", "IntEconomicrequirement"),],
                 replace_factors_int[[2]][c(7, 8, 9, 10)], dim_names = nice_dim_names_int[c(7, 8, 9, 10)], order_of_dimensions = c(3,2,1,4), 
                 xlim = c(0.35,0.65), legend_inset = c(-.3,-.2), show_legend = T, my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)],
                 increase_ylim = .2)
if(plots_to_pdf){dev.off()}
```


```{r, fig.height=9.5,fig.width=7.5}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_naturalization_mm_part1.pdf", height=11, width=7.5)}  
  custom_mm_plot(party_nat_mm[party_nat_mm$feature%in%c("NatPolicygoal", "NatLanguagerequirement", "NatIntegrationrequirement", "NatCitizenshipdescendents", "NatRequiredtimeresidence", "NatDualcitizenship"),], 
                 replace_factors_nat[[2]][c(1,2,4,5,8,9)], dim_names = nice_dim_names_nat[c(1,2,4,5,8,9)], order_of_dimensions = c(1,3,4,5,2,6), 
                 xlim = c(0.35,0.65), legend_inset = c(-.3,-.13), show_legend = T, my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)])
if(plots_to_pdf){dev.off()}
  
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_party_naturalization_mm_part2.pdf", height=8, width=7.5)}  
  custom_mm_plot(party_nat_mm[!party_nat_mm$feature%in%c("NatPolicygoal", "NatLanguagerequirement", "NatIntegrationrequirement", "NatCitizenshipdescendents", "NatRequiredtimeresidence", "NatDualcitizenship"),], 
                 replace_factors_nat[[2]][c(3,6,7)], dim_names = nice_dim_names_nat[c(3,6,7)], order_of_dimensions = c(1,3,2), 
                 xlim = c(0.35,0.65), legend_inset = c(-.3,-.2), show_legend = T, my_col = RColorBrewer::brewer.pal(6, "Set2")[c(3,5,1,4,6,2)],
                 increase_ylim = .25)
if(plots_to_pdf){dev.off()}  
```


## Subgroup Education


```{r education-cat-overview, echo=F, fig.width=6, include=F}
data$educ_quota_binary <- NA
data$educ_quota_binary <- ifelse(data$educ_quota=="low" | data$educ_quota=="medium", "Low/Medium",
                                 ifelse(data$educ_quota=="high", "High", NA))
quick_barplot(data$educ_quota_binary)   

conj_and_resp$educ_quota_binary <- NA
conj_and_resp$educ_quota_binary <- ifelse(conj_and_resp$educ_quota=="low" | conj_and_resp$educ_quota=="medium", "Low/Medium",
                                 ifelse(conj_and_resp$educ_quota=="high", "High", NA))
quick_barplot(conj_and_resp$educ_quota_binary)   
```

\newpage

### Three entry gates by education (amce)

```{r set-up-for-subgroup-education-plots}
amce_more_educ_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$educ_quota_binary =="High" & !is.na(conj_and_resp$educ_quota_binary),], respondent.id="resp_id")
amce_less_educ_immi <- cjoint::amce(formula = formular_exp1_Imm,
                data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$educ_quota_binary =="Low/Medium"  & !is.na(conj_and_resp$educ_quota_binary),], respondent.id="resp_id")
amce_more_educ_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$educ_quota_binary =="High"  & !is.na(conj_and_resp$educ_quota_binary),], respondent.id="resp_id")
amce_less_educ_int <- cjoint::amce(formula = formular_exp2_Int,
                data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$educ_quota_binary =="Low/Medium"  & !is.na(conj_and_resp$educ_quota_binary),], respondent.id="resp_id")
amce_more_educ_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$educ_quota_binary =="High"  & !is.na(conj_and_resp$educ_quota_binary),], respondent.id="resp_id")
amce_less_educ_nat <- cjoint::amce(formula = formular_exp3_Nat,
                data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$educ_quota_binary =="Low/Medium"  & !is.na(conj_and_resp$educ_quota_binary),], respondent.id="resp_id")

amce_more_educ_immi <- amce_replace_dim_names(amce_more_educ_immi, exp1_cat_labels, attr_names_exp1)  
amce_less_educ_immi <- amce_replace_dim_names(amce_less_educ_immi, exp1_cat_labels, attr_names_exp1) 

amce_more_educ_int <- amce_replace_dim_names(amce_more_educ_int, exp2_cat_labels, attr_names_exp2)  
amce_less_educ_int <- amce_replace_dim_names(amce_less_educ_int, exp2_cat_labels, attr_names_exp2) 

amce_more_educ_nat <- amce_replace_dim_names(amce_more_educ_nat, exp3_cat_labels, attr_names_exp3)  
amce_less_educ_nat <- amce_replace_dim_names(amce_less_educ_nat, exp3_cat_labels, attr_names_exp3) 

amce_educ_immi_attr <- list(amce_more_educ_immi$attributes,
                      amce_less_educ_immi$attributes)

amce_educ_immi_esti  <- list(amce_more_educ_immi$estimates,
                      amce_less_educ_immi$estimates)

dim_and_order_temp_1 <- dim_and_order_1
dim_and_order_temp_1$dim_names[4] <- "Economic requirement"

amce_educ_int_attr <- list(amce_more_educ_int$attributes,
                      amce_less_educ_int$attributes)

amce_educ_int_esti  <- list(amce_more_educ_int$estimates,
                      amce_less_educ_int$estimates)

dim_and_order_temp_2 <- dim_and_order_2
dim_and_order_temp_2$dim_names[6] <- "Economic requirement"

amce_educ_nat_attr <- list(amce_more_educ_nat$attributes,
                      amce_less_educ_nat$attributes)

amce_educ_nat_esti  <- list(amce_more_educ_nat$estimates,
                      amce_less_educ_nat$estimates)

dim_and_order_temp_3 <- dim_and_order_3
dim_and_order_temp_3$dim_names[7] <- "Economic requirement"
```

```{r subgroup-education, fig.height=9.5,fig.width=7.5, fig.cap='Subgroup analysis for more and less educated respondents. Reference categories are the most restricitve or demanding options.'}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_three_entry_gates_education.pdf", height=9.5, width=7)}
  layout(matrix(c(1,1,2,2,1,1,2,2,4,3,3,4,4,3,3,4), byrow=T, ncol=4))
  custom_amce_comparison(amce_educ_immi_attr, amce_educ_immi_esti, dim_and_order_temp_1, offset = 0.3, xlim=c(-0.23,0.2), plot_title = "Immigration", my_col = RColorBrewer::brewer.pal(3, "Set2")[1:2])
  custom_amce_comparison(amce_educ_int_attr, amce_educ_int_esti, dim_and_order_temp_2, offset = 0.3, xlim=c(-0.23,0.2), plot_title = "Integration", my_col = RColorBrewer::brewer.pal(3, "Set2")[1:2])
  custom_amce_comparison(amce_educ_nat_attr, amce_educ_nat_esti, dim_and_order_temp_3, legend_text= c("High education", "Low education"), offset = 0.3, legend_inset = c(-.2, -0.2), xlim=c(-0.23,0.2), plot_title = "Naturalization", my_col = RColorBrewer::brewer.pal(3, "Set2")[1:2])
if(plots_to_pdf){dev.off()}
```

```{r}
cjoint_amce_latex_output(list(amce_more_educ_immi, amce_less_educ_immi), dim_and_order_temp_1$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_more_educ_int, amce_less_educ_int), dim_and_order_temp_2$dim_names)
```

```{r}
cjoint_amce_latex_output(list(amce_more_educ_nat, amce_less_educ_nat), dim_and_order_temp_3$dim_names)
```

### Three entry gates by education (mm)

```{r educ-mm}
conj_and_resp_mm$educ_quota_binary <- NA
conj_and_resp_mm$educ_quota_binary <- as.factor(ifelse(conj_and_resp_mm$educ_quota=="low" | conj_and_resp_mm$educ_quota=="medium", "Low/Medium",
                                 ifelse(conj_and_resp_mm$educ_quota=="high", "High", NA)))

educ_imm_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Immchoice),],
          formula = formular_exp1_Imm, 
          id = ~ resp_id,
          by = ~ educ_quota_binary,
          estimate = "mm")

educ_int_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Intchoice),],
          formula = formular_exp2_Int, 
          id = ~ resp_id,
          by = ~ educ_quota_binary,
          estimate = "mm")

educ_nat_mm <- cregg::cj(data = conj_and_resp_mm[!is.na(conj_and_resp_mm$Natchoice),],
          formula = formular_exp3_Nat, 
          id = ~ resp_id,
          by = ~ educ_quota_binary,
          estimate = "mm")
```

```{r educ-mm-plot, fig.height=9.5, fig.width=9}
if(plots_to_pdf){pdf("output/output_figures_appendix/figure_three_entry_gates_education_mm.pdf", height=9.5, width=7)}
  layout(matrix(c(1,1,2,2,1,1,2,2,4,3,3,4,4,3,3,4), byrow=T, ncol=4))  
  custom_mm_plot(educ_imm_mm, replace_factors_imm[[2]], dim_names = nice_dim_names_imm, order_of_dimensions = c(1,3,4,2,8,5,6,9,10,7),
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), legend_text = F)
  custom_mm_plot(educ_int_mm, replace_factors_int[[2]], dim_names = nice_dim_names_int, order_of_dimensions = c(1,4,5,2,6,3,9,8,7,10), 
                 xlim = c(0.35,0.65), legend_inset = c(.28,-.15), legend_text = F)
  custom_mm_plot(educ_nat_mm, replace_factors_nat[[2]], dim_names = nice_dim_names_nat, order_of_dimensions = c(1,4,5,8,2,9,3,7,6), 
                 xlim = c(0.35,0.65), legend_inset = c(-.4,-.2), show_legend = T, legend_text = c("High education", "Low education"))
if(plots_to_pdf){dev.off()}
```


\newpage


```{r original-attention-check, echo=F}
conj_and_resp$failed_attention_check <- as.factor(conj_and_resp$failed_attention_check)
kable(cbind(
  tab_w_na(conj_and_resp$failed_attention_check[conj_and_resp$sample_name=="Pretest"])[,2],
  tab_w_na(conj_and_resp$failed_attention_check[conj_and_resp$sample_name=="MainSampleFirstHalf"])[,2],
  tab_w_na(conj_and_resp$failed_attention_check[conj_and_resp$sample_name=="300Extra"])[,2],
  tab_w_na(conj_and_resp$failed_attention_check[conj_and_resp$sample_name=="MainSampleSecondHalf"])[,2]),
  col.names = c("Pretest", "Main sample 1/3", "Additional 300", "Main sample 2/3"), caption="First attention check (Media usage)")
```

```{r second-check, echo=F}
conj_and_resp$failed_control_exp_3 <- as.factor(conj_and_resp$failed_control_exp_3)
kable(cbind(
  tab_w_na(conj_and_resp$failed_control_exp_3[conj_and_resp$sample_name=="Pretest"])[,2],
  tab_w_na(conj_and_resp$failed_control_exp_3[conj_and_resp$sample_name=="MainSampleFirstHalf"])[,2],
  tab_w_na(conj_and_resp$failed_control_exp_3[conj_and_resp$sample_name=="300Extra"])[,2],
  tab_w_na(conj_and_resp$failed_control_exp_3[conj_and_resp$sample_name=="MainSampleSecondHalf"])[,2]),
  col.names = c("Pretest", "Main sample 1/3", "Additional 300", "Main sample 2/3"), 
  caption="Second attention check (Previous policy)")
```

```{r both_att_checks, echo=F}
both_att_check <- table(conj_and_resp$failed_control_exp_3[conj_and_resp$sample_name=="MainSampleSecondHalf"], conj_and_resp$failed_attention_check[conj_and_resp$sample_name=="MainSampleSecondHalf"])
both_att_check <- both_att_check/sum(conj_and_resp$sample_name=="MainSampleSecondHalf")
rownames(both_att_check) <- c("2nd failed", "2nd passed")
kable(round(both_att_check,3), col.names = c("1st failed", "1st passed"), caption = "Cross table of both attention checks")
```

```{r regression-first-attention-check, echo=F, include=F}
conj_and_resp$sex_clear <- conj_and_resp$sex
conj_and_resp$sex_clear[conj_and_resp$sex=="-99"] <- NA
conj_and_resp$sex_clear <- factor(conj_and_resp$sex_clear, levels=c("Männlich", "Weiblich", "Divers"))
levels(conj_and_resp$sex_clear) <- c("Male", "Female", "Diverse")

reg_att_check1 <- glm(failed_attention_check~age_formated + sex_clear + educ_quota + left_right_clear, family = binomial, data=conj_and_resp[conj_and_resp$sample_name=="MainSampleSecondHalf" & !duplicated(conj_and_resp$resp_id),])
reg_att_check2 <- glm(failed_control_exp_3~age_formated + sex_clear + educ_quota + left_right_clear, family = binomial, data=conj_and_resp[conj_and_resp$sample_name=="MainSampleSecondHalf" & !duplicated(conj_and_resp$resp_id),])

conj_and_resp$combined_both_att_checks <- ifelse(conj_and_resp$failed_control_exp_3=="failed" & conj_and_resp$failed_attention_check=="failed", "failed",
                                                 ifelse(conj_and_resp$failed_control_exp_3=="passed" & conj_and_resp$failed_attention_check=="passed", "passed", NA))
conj_and_resp$combined_both_att_checks <- factor(conj_and_resp$combined_both_att_checks, levels=c("failed", "passed"))
reg_att_check3 <- glm(combined_both_att_checks~age_formated + sex_clear + educ_quota + left_right_clear, family = binomial, data=conj_and_resp[conj_and_resp$sample_name=="MainSampleSecondHalf" & !duplicated(conj_and_resp$resp_id),])
```

```{r output-regression-first-attention-check, echo=F, results='asis'}
stargazer(reg_att_check1, reg_att_check2, reg_att_check3,
          #type=stargazer_opt,
          #type="text",
          type="latex",
          title="Logistic regression for pass/fail attention check",
          dep.var.labels=c("Passed 1st","Passed 2nd", "Passed both"),
          covariate.labels = c("Age",
                               "Female",
                               "Diverse",
                               "Medium Educ.",
                               "High Educ.",
                               "Other Educ.",
                               "Left Right"),
          header=F
          )
```


```{r regression-table-main-figure}
reg_tab_mod_1 <- lm(formular_exp1_Imm, data=conj_and_resp[!is.na(conj_and_resp$Immchoice),])
reg_tab_mod_2 <- lm(formular_exp2_Int, data=conj_and_resp[!is.na(conj_and_resp$Intchoice),])
reg_tab_mod_3 <- lm(formular_exp3_Nat, data=conj_and_resp[!is.na(conj_and_resp$Natchoice),])

reg_tab_mod_1_passed_att_check <- lm(formular_exp1_Imm, data=conj_and_resp[!is.na(conj_and_resp$Immchoice) & conj_and_resp$failed_attention_check=="passed",])
reg_tab_mod_2_passed_att_check <- lm(formular_exp2_Int, data=conj_and_resp[!is.na(conj_and_resp$Intchoice) & conj_and_resp$failed_attention_check=="passed",])
reg_tab_mod_3_passed_att_check <- lm(formular_exp3_Nat, data=conj_and_resp[!is.na(conj_and_resp$Natchoice) & conj_and_resp$failed_attention_check=="passed",])

stargazer(reg_tab_mod_1, reg_tab_mod_1_passed_att_check, type="latex", no.space = T)
stargazer(reg_tab_mod_2, reg_tab_mod_2_passed_att_check, type="latex", no.space = T)
stargazer(reg_tab_mod_3, reg_tab_mod_3_passed_att_check, type="latex", no.space = T)
```

